#!/usr/bin/python
# -*- coding: utf-8 -*-

import subprocess
import os
import sys
import optparse
from lslconv_tools import cue_parse
from lslconv_tools import tags

#Define cli options parser
parser = optparse.OptionParser(
  usage="%prog [options] <target>\n",
  version="lslconv 0.1"
  )

parser.add_option("-o", "--output",
  action="store", type="string", dest="outcodec",
  metavar="CODEC",
  default="flac",
  help="Specify output codec (mp3 or flac).['%default']"
  )
parser.add_option("-n", "--name-format",
  action="store", type="string", dest="namingScheme",
  metavar="SCHEME",
  default="%n - %t",
  help="Specify naming scheme for generated files (%p - performer, %a - album, %n - track number, %t - title) ['%default']"
  )

(options, args) = parser.parse_args()

if len(args)!=1:
  sys.exit("Arguments miscount - there must be only one")

if not os.path.exists(args[0]):
  sys.exit("CUE sheet not found")

#converting cuesheet to utf-8 through iconv
subprocess.call(["iconv", "-fcp1251", "-tutf8", "-o"+args[0]+".utf", args[0]])  
#processing files
#using "FILE" param of cue sheet
cue_fp = open(args[0]+".utf")
cue = cue_parse.parse(cue_fp)

if not os.path.exists(cue['file']):
  sys.exit("Image for CUE sheet not found")
  
output = {
  'flac': "-o flac",
  'mp3': "-o cust ext=mp3 lame --quiet -b 320 -m s -h - %f"
}[options.outcodec]

retcode = subprocess.call(["shntool", "split", cue['file'], "-f"+args[0]+".utf", output, "-t"+options.namingScheme])

#writing tags
if options.outcodec == "flac":
  tags.tags_flac(cue)
elif options.outcodec == "mp3":
  tags.tags_mp3(cue)



